﻿using Newtonsoft.Json;
using System.Net;
using ZenSystemService.Api.Services;

namespace ZenSystemService.Api.Common
{
    public class ApiUtility
    {

        public static string ZenBright_BASE_URL;

        public static T? RequestPostApi<T>(string url, object param, out bool isSuccess, out string errMsg) where T : class
        {
            try
            {
                errMsg = "";
                Uri uri = new Uri(ZenBright_BASE_URL);
                HttpClient httpClient = new HttpClient();
                httpClient.BaseAddress = uri;

                var json = JsonConvert.SerializeObject(param);
                HttpContent httpContent = new StringContent(json);
                httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                var PushAction = httpClient.PostAsync(url, httpContent);
                var responseResult = PushAction.Result;
                if (responseResult.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    isSuccess = true;
                    var result = responseResult.Content.ReadAsStringAsync().Result;
                    httpClient.Dispose();
                    return JsonConvert.DeserializeObject<T>(result);
                }
                else
                {
                    errMsg = "调用接口出错:返回状态码:" + (int)responseResult.StatusCode;
                    isSuccess = false;
                    httpClient.Dispose();
                    return null;
                }
            }
            catch (Exception ex)
            {
                errMsg = "调用接口出错:" + ex.Message;
                isSuccess = false;
                return null;
            }
        }



        public static T? RequestGetApi<T>(string _url, out bool isSuccess, out string errMsg) where T : class
        {
            errMsg = "";
            // 目标GET接口的URL
            string url = ZenBright_BASE_URL + _url ;

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            // 接收报错信息
            HttpWebResponse resp;
            try
            {
                resp = (HttpWebResponse)req.GetResponse();
            }
            catch (WebException ex)
            {
                isSuccess = false;
                errMsg = ex.Message;
                return null;
            }

            if (resp.StatusCode == HttpStatusCode.OK)
            {

                Stream stream = resp.GetResponseStream();

                //获取内容
                using (StreamReader reader = new StreamReader(stream))
                {
                    string result = reader.ReadToEnd();// 请求结果
                    isSuccess = true;
                    return JsonConvert.DeserializeObject<T>(result);
                }
            }
            else
            {
                isSuccess = false;
                return null;
            }

        }

    }
}
